/**
* All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
*
* BaseShareManageService
* 共享管理
*
* 修改纪录
* 2020-08-27 版本：1.0 donghang 创建。
* @version 版本：1.0
* @author 作者：donghang
* 创建日期：2020-08-27
*/
package com.topscomm.base.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.mysql.jdbc.Clob;
import com.topscomm.base.BaseSystemConst;
import com.topscomm.base.pojo.BaseShareManageEntity;
import com.topscomm.base.service.IBaseShareManageService;
import com.topscomm.base.service.impl.auto.BaseShareManageServiceAuto;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboRoleEntity;
import com.topscomm.meet.MeetSystemConst.MeetShareTypeEnum;
import com.topscomm.meet.pojo.MeetManageEntity;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.tap.common.SessionUserBean;

@Service(value = "baseShareManageService")
@Scope(value = "singleton")
public class BaseShareManageService extends BaseShareManageServiceAuto implements IBaseShareManageService {
	@Autowired
	BaseTeamInfoService baseTeamInfoService;

	/**
	 * 通过类型查询初始化的文件共享list
	 *
	 * @description:
	 * @param sharetypeList
	 * @return
	 * @author: donghang
	 * @date: 2020年8月27日上午9:31:59
	 * @modify:
	 */
	@Override
	public List<Map<String, Object>> queryDefaultList(List<Map<String, Object>> sharetypeList) {
		return null;
	}

	/**
	 * 通过类型查询记录，并置初始化
	 *
	 * @description:
	 * @param sharetypeList
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2020年8月27日上午9:32:30
	 * @modify:
	 */
	@Override
	public List<Map<String, Object>> queryListBySourceType(List<Map<String, Object>> sharetypeList,
			Map<String, Object> paraMap) {
		// sharetypeList赋默认值
		sharetypeList.forEach(map -> {
			map.remove("id");
			map.put("sharetype", ConvertUtil.convertToString(map.get("code")));
			map.put("dispsharetype", ConvertUtil.convertToString(map.get("name")));
		});
		String sourceId = ConvertUtil.convertToString(paraMap.get("sourceid"));
		String sourceType = ConvertUtil.convertToString(paraMap.get("sourcetype"));
		if (sourceId == null || "".equals(sourceId)) {
			return sharetypeList;
		}

		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" sourceId = '{0}' and sourceType = '{1}' ", sourceId, sourceType);
		List<Map<String, Object>> listMap = this.queryMapByWhere(sql.toString());
		addShareInfo(sharetypeList, listMap);
		return sharetypeList;
	}

	/**
	 * @description: 添加共享信息
	 * @param sharetypeList
	 * @param listMap
	 * @author: wanghongwei
	 * @date: 2020年9月2日上午11:32:08
	 * @modify:
	 */
	private void addShareInfo(List<Map<String, Object>> sharetypeList, List<Map<String, Object>> listMap) {
		for (int i = 0; i < sharetypeList.size(); i++) {
			Map<String, Object> shareMap = sharetypeList.get(i);
			String shareType = ConvertUtil.convertToString(shareMap.get("sharetype"));
			for (Map<String, Object> map : listMap) {
				String queryShareType = ConvertUtil.convertToString(map.get("sharetype"));
				if (Objects.equals(shareType, queryShareType)) {
					sharetypeList.set(i, map);
					break;
				}
			}
		}
	}

	/**
	 * @description: 插入共享记录
	 * @param listMap
	 * @param isDelete
	 * @author: wanghongwei
	 * @date: 2020年8月27日上午10:17:11
	 * @modify:
	 */
	@Override
	public void insertDataList(List<Map<String, Object>> listMap, boolean isDelete) {
		if (listMap.size() > 0 && isDelete) {
			String sourceID = ConvertUtil.convertToString(listMap.get(0).get("sourceid"));
			List<Map<String, Object>> oldFileshareList = this.queryMapByWhere("sourceid=" + sourceID);
			StringBuilder builder = new StringBuilder();
			oldFileshareList.forEach(map -> {
				builder.append(ConvertUtil.convertToString(map.get("id")));
				builder.append(",");
			});
			if (builder.length() > 0) {
				String ids = builder.substring(0, builder.length() - 1);
				this.deleteByWhere(" id in (" + ids + ")");
			}
		}
		List<BasicEntity> listEntity = new ArrayList<>();
		listMap.forEach(map -> {
			if (map.get("sharedeptcodes") == null && map.get("shareroleids") == null && map.get("shareteamids") == null
					&& map.get("shareusercodes") == null) {
				return;
			}
			BaseShareManageEntity entity = new BaseShareManageEntity();
			entity.convertFromMap(map);
			if (MeetShareTypeEnum.Attend.equals(entity.getSharetype())) {
				this.setAllSelectUser(entity);
			}
			entity.setId(0L);
			listEntity.add(entity);
		});
		if (listEntity.size() > 0) {
			this.insertBatch(listEntity);
		}
	}

	/**
	 * 通过选择的部门、团队、角色、人员等查询所有的人员
	 *
	 * @description:
	 * @return
	 * @author: donghang
	 * @date: 2020年9月3日上午10:18:52
	 * @modify:
	 */
	public void setAllSelectUser(BaseShareManageEntity baseShareManageEntity) {
		BaseCboUserExtendService baseCboUserExtendService = (BaseCboUserExtendService) SpringUtil
				.getBean("baseCboUserExtendService");
		BaseTeamInfoService baseTeamInfoService = (BaseTeamInfoService) SpringUtil.getBean("baseTeamInfoService");
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		String sharedeptcodes = baseShareManageEntity.getSharedeptcodes();
		String shareroleids = baseShareManageEntity.getShareroleids();
		String shareteamids = baseShareManageEntity.getShareteamids();
		String shareusercodes = baseShareManageEntity.getShareusercodes();
		String shareusernames = baseShareManageEntity.getShareusernames();
		if (!StringUtil.isEmpty(sharedeptcodes)) {
			List<Map<String, Object>> userList = baseCboUserExtendService.searchUsersByDeptCodes(sharedeptcodes);
			for (Map<String, Object> map1 : userList) {
				map1.put("usercode", map1.remove("code"));
				map1.put("username", map1.remove("name"));
			}
			resultList.addAll(userList);
		}
		if (!StringUtil.isEmpty(shareroleids)) {
			List<Map<String, Object>> userList = baseCboUserExtendService.searchUserByRoleIds(shareroleids);

			for (Map<String, Object> map1 : userList) {
				map1.put("usercode", map1.remove("code"));
				map1.put("username", map1.remove("name"));
			}
			resultList.addAll(userList);
		}
		if (!StringUtil.isEmpty(shareteamids)) {
			List<Map<String, Object>> userList = baseTeamInfoService.getTeamMembers(shareteamids);
			resultList.addAll(userList);
		}
		List<String> userCodeList = resultList.stream()
				.map(userMap -> ConvertUtil.convertToString(userMap.get("usercode"))).distinct()
				.collect(Collectors.toList());
		String selectUserCodes = String.join(",", userCodeList);
		if (!StringUtil.isEmpty(shareusercodes)) {
			if (!StringUtil.isEmpty(selectUserCodes)) {
				selectUserCodes += "," + shareusercodes;
			} else {
				selectUserCodes = shareusercodes;
			}
		}
		List<String> userNameList = resultList.stream()
				.map(userMap -> ConvertUtil.convertToString(userMap.get("username"))).distinct()
				.collect(Collectors.toList());
		String selectUserNames = String.join(",", userNameList);
		if (!StringUtil.isEmpty(shareusernames)) {
			if (!StringUtil.isEmpty(selectUserNames)) {
				selectUserNames += "," + shareusernames;
			} else {
				selectUserNames = shareusernames;
			}
		}
		baseShareManageEntity.setAllusernames(selectUserNames);
		baseShareManageEntity.setAllusercodes(selectUserCodes);
	}

	/**
	 * @description: 删除文件共享信息
	 * @param listSourceId
	 * @param sourceType
	 * @author: wanghongwei
	 * @date: 2020年8月27日上午9:09:14
	 * @modify:
	 */
	@Override
	public void deleteBySource(List<String> listSourceId, String sourceType) {
		if (listSourceId == null || listSourceId.size() <= 0) {
			return;
		}
		for (String sourceId : listSourceId) {
			deleteBySource(sourceId, sourceType);
		}
	}

	/**
	 * 通过人员查询组织where语句
	 *
	 * @description:
	 * @param usercode
	 * @return
	 * @author: donghang
	 * @date: 2020年8月27日下午1:33:54
	 * @modify:
	 */
	@Override
	public String createShareWhereCondition(SessionUserBean sessionUserBean) {
		StringBufferProxy sqlWhere = new StringBufferProxy();
		// 人员
		sqlWhere.appendSingle("  (','||shareusercodes||',') like '%{0}%' ",
				"," + sessionUserBean.getUser().getCode() + ",");
		// 角色
		List<CboRoleEntity> cboRoleEntityList = sessionUserBean.getRoleList();
		for (CboRoleEntity cboRoleEntity : cboRoleEntityList) {
			sqlWhere.appendSingle(" or {0} like '%{1}%' ", "shareroleids", cboRoleEntity.getId());
		}
		// 部门,包含下级部门
		String deptcodesql = this.createWhereDeptCheckInclude("sharedeptcodes", sessionUserBean.getDept().getCode(),
				",");
		if (deptcodesql.length() > 0) {
			sqlWhere.appendSingle(" or {0}", deptcodesql);
		}
		// 团队
		// 查看当前人所在的所有团队
		Map<String, Object> userTeamMap = this.baseTeamInfoService.getUserTeam(sessionUserBean.getUser().getCode());
		StringBufferProxy teamPermissionWhereSql = new StringBufferProxy();
		for (Map.Entry<String, Object> entry : userTeamMap.entrySet()) {
			String teamId = entry.getKey();
			Map<String, Object> teamMap = (Map<String, Object>) entry.getValue();
			if (!BaseSystemConst.TeamUserTypeEnum.Director.equals(ConvertUtil.convertToString(teamMap.get("usertype")))
					&& ConvertUtil.convertToString(teamMap.get("positionbegintime")).length() > 0) {
				teamPermissionWhereSql.appendSingle("or ({0} like '%{1}%' and begintime>={2}) ", "shareteamids", teamId,
						SQLAdapter.toDateLong(DateUtil.dateToString(
								DateUtil.stringToDate(ConvertUtil.convertToString(teamMap.get("positionbegintime"))),
								"yyyy-MM-dd HH:mm:ss")));
			} else {
				teamPermissionWhereSql.appendSingle("or {0} like '%{1}%' ", "shareteamids", teamId);
			}

		}
		if (teamPermissionWhereSql.toString().length() > 0) {
			StringBufferProxy teamPermissionSql = new StringBufferProxy();
			teamPermissionSql.appendSingle(
					"select id from (select meetmanage.id as id, shareteamids,begintime from meetmanage,basesharemanage where  meetmanage.id = basesharemanage.sourceid and  basesharemanage.sourcetype='{0}'  and ({1}) )",
					MeetManageEntity.tableName, teamPermissionWhereSql.toString().substring(2));
			sqlWhere.appendSingle(" or sourceid in({0})", teamPermissionSql.toString());
		}
		return sqlWhere.toString();
	}

	/**
	 *
	 * @description:
	 * @param colname
	 * @param deptautocode
	 * @param spiltstring
	 * @return
	 * @author: donghang
	 * @date: 2020年8月27日下午1:40:53
	 * @modify:
	 */
	public static String createWhereDeptCheckInclude(String colname, String deptautocode, String spiltstring) {
		StringBufferProxy sql = new StringBufferProxy();
		if (StringUtil.isEmpty(colname) || StringUtil.isEmpty(deptautocode))
			return "";
		int start_num = 0;
		if (deptautocode.trim().indexOf("_") < 0)
			start_num = 2;
		else
			start_num = deptautocode.indexOf("_") + 3;
		String[] params = { "'" + spiltstring + "'", colname, "'" + spiltstring, "'" };
		for (int i = start_num; i <= deptautocode.length(); i = i + 2) {
			sql.appendSingle("or {0} like '%{1}%' ", SQLAdapter.concat(params),
					spiltstring + deptautocode.substring(0, i) + spiltstring);
		}
		String whereSql = "(" + sql.toString().substring(2) + ")";
		return whereSql;
	}

	/**
	 * @description: 删除文件共享信息
	 * @param sourceId
	 * @param sourceType
	 * @author: wanghongwei
	 * @date: 2020年8月27日下午5:15:51
	 * @modify:
	 */
	private void deleteBySource(String sourceId, String sourceType) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" sourceId = '{0}' and sourceType = '{1}' ", sourceId, sourceType);
		List<BaseShareManageEntity> listBaseShareManageEntity = this.queryByWhere(sql.toString());
		// 遍历删除
		for (BaseShareManageEntity entity : listBaseShareManageEntity) {
			this.deleteById(ConvertUtil.convertToString(entity.getId()));
		}
	}

	/**
	 * 查询用户是否在范围内
	 *
	 * @description:
	 * @param baseShareManageEntity
	 * @param userCode
	 * @return
	 * @author: donghang
	 * @date: 2020年9月1日下午5:58:55
	 * @modify:
	 */
	@Override
	public boolean queryIsVisible(BaseShareManageEntity baseShareManageEntity, SessionUserBean sessionUserBean) {

		// 1.查询人员是否在所选择范围内
		String[] usercodes = ConvertUtil.convertToString(baseShareManageEntity.getShareusercodes()).split(",");
		List<String> userCodeList = Arrays.asList(usercodes); // 此集合无法操作添加元素
		String userCode = sessionUserBean.getUser().getCode();
		if (userCodeList.contains(userCode)) {
			return true;
		}
		// 2.查询人员角色是否在选择范围内
		String[] roleids = ConvertUtil.convertToString(baseShareManageEntity.getShareroleids()).split(",");
		List<String> visibleRoleList = Arrays.asList(roleids);
		List<CboRoleEntity> userRoleList = sessionUserBean.getRoleList();
		for (CboRoleEntity cboRoleEntity : userRoleList) {
			if (visibleRoleList.contains(ConvertUtil.convertToString(cboRoleEntity.getId()))) {
				return true;
			}
		}
		// 3.查询人员所在团队是否在选择范围内
		Map<String, Object> userTeams = baseTeamInfoService.getUserTeam(userCode);
		String[] teamids = ConvertUtil.convertToString(baseShareManageEntity.getShareteamids()).split(",");
		List<String> visibleTeamList = Arrays.asList(teamids);
		for (Map.Entry<String, Object> team : userTeams.entrySet()) {
			String teamid = team.getKey();
			if (visibleTeamList.contains(teamid)) {
				return true;
			}
		}
		// 4.查询部门是否在选择范围内
		String[] visibleDeptcodes = ConvertUtil.convertToString(baseShareManageEntity.getSharedeptcodes()).split(",");
		List<String> visibleDeptcodesList = Arrays.asList(visibleDeptcodes);
		String deptCode = sessionUserBean.getDept().getCode();
		if (visibleDeptcodesList.size() > 0) {
			int start_num = 0;
			for (int i = start_num; i <= deptCode.length(); i = i + 2) {
				int endIndex = i + 2;
				// 为了避免substring(0, endIndex)出现空指针异常，先判断是否超出长度
				if (endIndex <= deptCode.length() && visibleDeptcodesList.contains(deptCode.substring(0, endIndex))) {
					return true;
				}
			}
		}
		return false;
	}
}
